<template>
  <el-container style="height: 100%">
    <el-main>
      <el-table
        ref="tableRef"
        style="height: 100%"
        highlight-current-row
        :data="tableProps.data"
        @current-change="handleCurrentRowChange"
        :row-class-name="tableRowClassName"
      >
        <el-table-column
          type="index"
          width="50"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="Name"
          label="姓名"
          align="center"
          header-align="center"
        />
        <!-- 0 男 1 女 -->
        <el-table-column
          prop="Sex"
          label="性别"
          align="center"
          header-align="center"
        >
          <template #default="{ row }"
            >{{ row.Sex === 1 ? "女" : "男" }}
          </template>
        </el-table-column>
        <el-table-column
          prop="Time"
          label="时间"
          align="center"
          header-align="center"
        />
        <el-table-column
          prop="ID"
          label="序号"
          align="center"
          header-align="center"
        />
      </el-table>
    </el-main>
    <el-aside width="500px">
      <UserCard v-model:user-data="userInfo" type="gun"></UserCard>
      <br />
      <el-card>
        <el-form>
          <el-form-item label="仪器型号">
            <el-select v-model="dataType">
              <el-option value="">未选择</el-option>
              <el-option
                v-for="(item, index) in selectList"
                :key="index"
                :value="item.type"
                :label="item.name"
                >{{ item.name }}</el-option
              >
            </el-select>
          </el-form-item>
          <el-form-item label="检测日期">
            <ElDatePicker
              v-model="date"
              :clearable="false"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            >
            </ElDatePicker>
          </el-form-item>
        </el-form>
        <el-row>
          <el-col :span="6">仪器型号：</el-col>
          <el-col :span="18"></el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-button type="success" @click="handleImportData"
              >数据导入
            </el-button>
          </el-col>
          <el-col :span="16">
            计数：
            <el-tag>{{ leftModel.total }}</el-tag>
          </el-col>
        </el-row>
      </el-card>
      <ElCard :body-style="{ textAlign: 'center' }">
        <!-- <ElButton type="primary" @click="handleSave">
          <ElIcon> <CircleCheck /> </ElIcon>保存
        </ElButton> -->
        <!--        <el-button-->
        <!--          type="info"-->
        <!--          @click="asyncHandle"-->
        <!--          loading-icon="Eleme"-->
        <!--          :loading="asyncLoading"-->
        <!--          >配置管理-->
        <!--        </el-button>-->
        <el-button
          type="warning"
          @click="asyncHandle"
          loading-icon="Eleme"
          :loading="asyncLoading"
          >同步
        </el-button>
        <LocalHistoryList
          :table="db.biochemical"
          @edit-click="handleHistoryRowEdit"
          :edit-btn="false"
        />
      </ElCard>
    </el-aside>
  </el-container>
</template>

<script setup lang="ts">
import UserCard from "@/components/UserCard/index.vue";
import { onMounted, reactive, ref, toRaw, watch } from "vue";
import {
  transformFromCSV,
  transformFromXlsb,
  useTransformByKey,
} from "@/views/Biochemical/FileTransformUtils";
import { dayjs, ElMessage, ElTable } from "element-plus";
import { ipcRenderer } from "electron";
import { db, DbService } from "@/db/db";
import { createBiochemicalCloud } from "@/model/TerminalType";
import { asyncBiochemical } from "@/api/asyncApi";
import LocalHistoryList from "@/components/LocalHistoryList/index.vue";
import { useTerminalAsync } from "@/hooks/useTerminalAsync";

type ISelect = Array<{
  type: string;
  name: string;
  path: string;
  transform?: string;
}>;
const selectList = ref<ISelect>();

// 获取配置文件中的内容
ipcRenderer.send("get-config-file");
ipcRenderer.once("config-file-done", (event, list) => {
  console.log(event, list);
  selectList.value = list.biochemicalList as ISelect;
});

/**
 * 基本逻辑，扫码，比对姓名，如果姓名正确，自动保存
 */
// 仪器类型
const dataType = ref("");
// 搜索时间
const date = ref(dayjs().format("YYYY-MM-DD"));
// 表格
const tableRef = ref<InstanceType<typeof ElTable>>();
// 上传用的input框
// 处理导入按钮
const handleImportData = () => {
  if (!dataType.value) return ElMessage.error("请先选择仪器型号");
  const device = selectList.value?.find((item) => item.type === dataType.value);
  switch (device?.type) {
    case "sqlite":
      handleSqliteImport({
        type: "sqlite",
        path: device.path,
        queryDate: date.value,
        transform: device.transform,
      });
      break;
    case "input:csv":
      handleInputImport(transformFromCSV, useTransformByKey(device.transform));
      break;
    case "input:xlsb":
      console.log(device);
      handleInputImport(transformFromXlsb, useTransformByKey(device.transform));
      break;
  }
};
// sqlite导入
const handleSqliteImport = (config) => {
  ipcRenderer.send("load-sqlite-data", config);
  ipcRenderer.once("send-sqlite-data", handleSqliteSendData);
};
// 获取到数据后清空
const handleSqliteSendData = (e, data) => {
  setTableData(data);
};
//
const setTableData = (data: any) => {
  if (data.length === 0) {
    ElMessage.warning("导入0条数据");
  }
  tableProps.data = data;
  leftModel.total = data.length;
  tableRef.value?.setCurrentRow(data[0]);
};

const leftModel = reactive({
  total: 0,
});

const handleInputImport = (loadFunction, transform?: Function) => {
  const input = document.createElement("input");
  input.type = "file";
  input.oninput = async (e) => {
    const target = e.target as HTMLInputElement;
    const files = target.files || [];
    const file = files[0];
    const json = await loadFunction(file);
    if (json) {
      setTableData(transform ? transform(json) : json);
    }
  };
  input.dispatchEvent(new MouseEvent("click"));
};

const tableProps = reactive<{ data: Array<any> }>({
  data: [],
});

const userInfo = ref();
const bindKey = (target: Object, source: Object) => {
  Object.keys(target).forEach((item) => {
    if (source.hasOwnProperty(item)) {
      target[item] = source[item];
    }
  });
};
watch(userInfo, (newVal) => {
  console.log(newVal);
  if (newVal.id) {
    handleScanSuccess(newVal);
  }
});
const dbService = new DbService(db.biochemical);
const handleScanSuccess = async (user) => {
  if (tableCurrentRow) {
    // if (tableCurrentRow.Name === user.username) {
    userInfo.value = user;
    const cloudRow = createBiochemicalCloud();
    bindKey(cloudRow, tableCurrentRow);
    cloudRow.article = "血球";
    delete cloudRow.id;
    const result = await dbService.saveCard(cloudRow, toRaw(userInfo.value));
    ElMessage.success(cloudRow.userName + "数据保存成功");
    tableCurrentRow.bindState = 1;
    const index = tableProps.data.findIndex(
      (item) => item.ID === tableCurrentRow.ID
    );
    tableRef.value?.setCurrentRow(tableProps.data[index + 1]);
  } else {
    ElMessage.error("请先选中一行，再扫码");
  }
};

const handleSave = () => {};
const handleAsync = () => {};

const tableRowClassName = ({ row, rowIndex }) => {
  if (row.bindState === 1) {
    return "success-row";
  }
  return "";
};
// 匹配逻辑
let tableCurrentRow;
const handleCurrentRowChange = async (currentRow, oldCurrentRow) => {
  tableCurrentRow = currentRow;
};

const { asyncHandle, asyncLoading } = useTerminalAsync(
  db.biochemical,
  asyncBiochemical
);

// 历史记录
const handleHistoryRowEdit = (row) => {
  // formModel.value = row;
  // qrScanInfo.value = {
  //   id: row.qr_code_id,
  //   username: row.userName,
  //   sex: row.sex,
  //   idno: row.cardId,
  // };
};
</script>

<style scoped>
:deep(.el-table__body tr.current-row > td) {
  background-color: #69a8ea !important;
  color: #fff;
}

:deep(.el-table .success-row) {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}
</style>
